$(function () {
    $(document).keyup(function (e) {
        if (e.which == 13) {
            $('#selectBtnEnter').click();
        }
    })
});
var path = '../';
var pageListUrl = path + 'wxActivity/list';
var pageUrl = path + 'wxActivity/';
//添加弹窗
var addPanel = null;
var addPanelPicture = null;
// ---------------交互代码begin-----------------
//本页面业务逻辑
var wxActivity = {
    checkLogic: function (dataObj) {
        var result = "";
        var isSubmit = true;
        $.each(dataObj, function (key) {
            if (key.indexOf('Err') != -1 && dataObj[key].length > 0) {
                return false;
            }
        });
        dataObj.imgErr = "";
        dataObj.desErr = "";
        dataObj.activityDateStartErr = "";
        dataObj.activityDateEndErr = "";
        result = customUtils.checkLen(dataObj.des, 1, 100, '描述信息长度不对');
        if (result.length != 0) {
            dataObj.desErr = result;
            isSubmit = false;
        }
        result = customUtils.checkLen(dataObj.activityDateStart, 1, 32, '活动开始时间长度不对');
        if (result.length != 0) {
            dataObj.activityDateStartErr = result;
            isSubmit = false;
        }
        result = customUtils.checkLen(dataObj.activityDateEnd, 1, 32, '活动开始结束长度不对');
        if (result.length != 0) {
            dataObj.activityDateEndErr = result;
            isSubmit = false;
        }
        var isSubmit = true;
        var img = $("#file")[0].files[0];
        //文件空校验
        if (!img) {
            dataObj.imgErr = "请选择要上传的展示图片";
            isSubmit = false;
        }
        //文件格式校验
        var imgType = ["jpg", "png", "gif", "jpeg", "bmp"];
        if (img) {
            var type = img.name.substr(img.name.lastIndexOf(".") + 1, img.name.length).toLowerCase();
            if ($.inArray(type, imgType) == '-1') {
                dataObj.imgErr = "请上传" + imgType.toString() + "格式的图片";
                isSubmit = false;
            }
        }
        //检查表单是否存在错误
        $.each(dataObj, function (key) {
            if (key.indexOf('Err') != -1 && dataObj[key].length > 0) {
                isSubmit = false;
            }
        });
        return isSubmit;
    }
};

var dataList = new Vue({
    el: "#wxActivityList",
    data: {
        pageInfo: {},
        detail: {},
        condition: {
            page: 1,
            rows: customUtils.pageSize,
            total: 0,
            items: [],
            all: false,
            id: "",
            img: "",
            des: "",
            md5: "",
            activityDateStart: "",
            activityDateEnd: ""
        },
        //自定义条件查询---end--------
        selectIds: [],//多选
        showSuccess: false,//false不显示成功提示
        selectedIdx: -1,//保存操作行的索引
        isSearch: false,//init:页面初始化；search:点击查询；paging:点击翻页；changePageSize:改变页面显示条数
        selectedPageSize: customUtils.pageSize//修改页面数据显示条数
    },
    mounted: function () {
        this.getList('init');
    },
    // 在 `methods` 对象中定义方法,如果操作中函数的逻辑比较复杂，必须封装到dictType对象
    methods: {
        selectChkBtn: function (e) {//用于多选事件
            this.selectIds.push($(e.target).val());
        },
        //搜索、分页列表
        getList: function (eventSrc) {
            var self = this;
            //改变页面显示条数
            if (eventSrc == "changePageSize") {
                if (this.pageInfo.pageSize != this.selectedPageSize) {
                    this.pageInfo.pageSize = this.selectedPageSize;
                    $('#pagination').jqPaginator('destroy');
                    eventSrc = 'init';//重新绘制控件
                } else {
                    return;
                }
            }
            var param = {"page": 1, "rows": customUtils.pageSize};
            //初始化时无当前页数，后台有默认第1页，每页10条
            if (this.pageInfo != undefined && this.pageInfo.pageNum != undefined) {
                self.condition["page"] = this.pageInfo.pageNum;
                self.condition["rows"] = this.pageInfo.pageSize;
            }
            param["page"] = self.condition["page"];
            param["rows"] = self.condition["rows"];
            this.condition.items = [];
            console.log(param)
            //发送请求,第一个参数http对象，第二个是url，第三个是参数，第四个是成功回调，第五个是请求失败回调
            customUtils.post(self, pageListUrl, param, function (response, isSuccess) {
                if (isSuccess == false) {
                    dataList.pageInfo.pages = 0;
                    customUtils.noData('无数据', 0);
                    return;
                }
                dataList.pageInfo = response.body.pagination;
                customUtils.noData('无数据', dataList.pageInfo.pages);
                //页面初始化、搜索时，才需要执行分页控件
                if (eventSrc == 'init' || eventSrc == 'search') {
                    customUtils.paging('#pagination', dataList.pageInfo.pages, customUtils.showPage, function (num) {
                        //当前页码pageNum与将要翻页的页码num不相等才执行，否则为同一页
                        if (dataList.pageInfo.pageNum != num) {
                            dataList.pageInfo.pageNum = num;
                            dataList.getList('paging');
                        }
                    });
                }
            }, function (response) {
                console.log(response);
                dataList.pageInfo.pages = 0;
                customUtils.noData('无数据', 0);
            });
        },
        //打开添加对话框
        addOrUpdatePanel: function (flag) {
            //清除表单数据，否则会有前一条修改数据的内容
            $.each(addOrUpdate.$data, function (key) {
                addOrUpdate[key] = "";
            });
            var tmpTitle = flag == "add" ? "添加" : "修改";
            addPanel = layer.open({
                type: 1,
                title: tmpTitle + "活动展示图片",
                area: ['570px', 'auto'],
                shadeClose: false, // 点击遮罩关闭
                content: $('#addPanel')
            });
        },
        del: function (index) {
            var msg = "你确定要删除这条数据么";
            var self = this;
            layer.confirm(msg, function (idx) {
                var record = dataList.pageInfo.list[index];
                var param = {id: record.id};
                customUtils.post(self, pageUrl + 'delete', param, function (response, isSuccess) {
                    customUtils.showTips(response.body, null, 3000);
                    dataList.getList("no");
                }, function (response) {
                    console.log(response.body);
                });
                layer.close(idx);
                return true;
            });
        },
        //初始化更新，更新对话框
        updateInit: function (index) {
            //先显示窗口，才有加载效果
            this.addOrUpdatePanel("update");
            var record = this.pageInfo.list[index];
            this.selectedIdx = index;
            var url = pageUrl + 'id/' + record.id;
            var self = this;
            customUtils.get(self.$http, url, function (response, isSuccess) {
                if (isSuccess == false) {
                    return;
                }
                //回显表单数据
                $.each(response.body, function (key) {
                    if (addOrUpdate[key] != undefined) {
                        addOrUpdate[key] = response.body[key];
                    }
                });
            }, function (response) {
                console.log(response);
            });
        },
        reset: function () {
            $.each(addOrUpdate.$data, function (key) {
                addOrUpdate[key] = "";
            });
        }
    }
});

//新增或更新---------begin-------
var addOrUpdate = new Vue({
    el: "#addPanel",
    data: {
        id: "",
        des: "",
        img: "",
        md5: "",
        activityDateStart: "",
        activityDateEnd: "",
        imgErr: "",
        activityDateEndErr: "",
        activityDateStartErr: "",
        desErr: "",
        showSuccess: true,//显示成功提示
        field: {
            id: "",
            imgErr: "",
            activityDateEndErr: "",
            activityDateStartErr: "",
            desErr: ""
        },
        //错误信息
        err: {
            id: "",
            imgErr: "",
            activityDateEndErr: "",
            activityDateStartErr: "",
            desErr: ""
        }
    },
    //当需要在数据变化时执行异步或开销较大的操作时，这个方式是最有用的
    watch: {},
    methods: {
        upload: function (e) {
            console.log(this.id)
            //逻辑校验
            if (!wxActivity.checkLogic(this.$data)) {
                return;
            }
            if (this.id == "") {
                var formDate = new FormData($("#addPanel")[0]);
                console.log(formDate);
                var loading = layer.load(0, {shade: [0.5, '#949494']});
                $.ajax({
                    url: pageUrl + "upload",
                    type: "POST",
                    dataType: "json",
                    cache: false,
                    data: formDate,
                    processData: false,
                    contentType: false
                }).done(function (res) {
                    layer.close(loading);
                    console.log(res);
                    addOrUpdate.$data.img = res.img;
                    addOrUpdate.$data.md5 = res.md5;
                    addOrUpdate.save();
                }).fail(function (res) {
                    layer.close(loading);
                    console.log("上传失败");
                });
            } else {
                this.save();
            }
        },
        save: function () {
            //没有id的时候表示新增，否则为更新
            var actionUrl = this.id == "" ? 'save' : 'update';
            var self = this;
            var msg = "您确定要将" + actionUrl + " 1条位置信息";
            layer.confirm(msg, function (index) {
                customUtils.post(self, pageUrl + actionUrl, self.$data, function (response, isSuccess) {
                    customUtils.showTips(response.body, addOrUpdate.$data.err)
                    dataList.getList('init');
                    if (isSuccess && addPanel) layer.close(addPanel);
                }, function (res) {
                    customUtils.showRequestTips(response, 3000)
                });
                layer.close(index);
                return true;
            });
        },
        changeTime: function (elem) {
            this.$data[elem.split("-")[0]] = $("#" + elem).val();
        },
        //全选--取消全选方法
        checkAll: function () {
            console.log(this.condition);
            if (this.condition.all) {
                this.condition.all = false;
                $("tbody").find("input[type='checkbox'][name='id']").each(function (i, val) {
                    dataList.condition.items = [];
                });
            } else {
                this.condition.all = true;
                $("tbody").find("input[type='checkbox'][name='id']").each(function (i, val) {
                    dataList.condition.items[i] = val.value;
                });
            }
        },
        //清除表单数据
        reset: function () {
            $.each(addOrUpdate.$data, function (key) {
                addOrUpdate[key] = "";
            });
        },
        resetPicture: function () {
            if (addPanelPicture) layer.close(addPanelPicture);
        }
    }
});

